package com.ygqh.baby.interceptor;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.CodeConstant;
import com.ygqh.baby.ao.ResponseEntity;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.model.YgLoginModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class AppExceptionHandler {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 基于@ExceptionHandler异常处理
     *
     * @param <T>
     */
    @ExceptionHandler
    @ResponseBody
    public ResponseEntity execute(HttpServletRequest request, HttpServletResponse response, Exception ex) {

        if (ex instanceof YgException) {
            YgException e = (YgException) ex;
            if ("002".equals(e.getErrorCode())) {
                return new ResponseEntity("002", "请跳转至登陆页", new YgLoginModel("REDIRECT_LONGIN_PAGE", "请跳转至登陆页"));
            }
        }
        String methodName = request.getRequestURI();
        Map<String, String[]> parameterMap = request.getParameterMap();
        String param = JSON.toJSONString(parameterMap);

        StringBuilder sb = new StringBuilder();
        StackTraceElement[] st = ex.getStackTrace();
        sb.append("【methodName】=" + methodName).append(";【param】=" + param + "</br>")
                .append("【异常类型】:" + ex.getClass().getName() + "【" + ex.getMessage() + "】</br>");
//		for (StackTraceElement stackTraceElement : st) {
//			String exclass = stackTraceElement.getClassName();
//			String method = stackTraceElement.getMethodName();
//			if (exclass.contains("com.ygqh.baby")) {
//				sb.append(DateConvertUtils.formatDateTime(new Date()) + ":" + "[类:" + exclass + "]调用" + method + "时在第" + stackTraceElement.getLineNumber()
//						+ "行代码处发生异常!");
//			}
//		}
        ex.printStackTrace();
        logger.error(sb.toString(), ex);
        return new ResponseEntity(CodeConstant.Error.getCode(), CodeConstant.Error.getTitle(), ex.getMessage());
    }
}
